<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.nickName" placeholder="帐号" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column prop="id" label="ID" sortable align="center" width="80" />
      <el-table-column prop="username" label="帐号" align="center" />
      <el-table-column prop="nickName" label="姓名" align="center" />
      <el-table-column prop="storeId" label="店铺ID" align="center" />
      <el-table-column prop="storeName" label="店铺名称" align="center" />
      <el-table-column prop="note" label="备注" align="center" />
      <el-table-column label="操作" align="center" width="250" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">

        <el-form-item label="帐号" prop="username">
          <el-input v-model="temp.username" />
        </el-form-item>
        <el-form-item v-if="dialogStatus=='create'" label="密码" prop="password">
          <el-input v-model="temp.password" />
        </el-form-item>
        <el-form-item label="姓名" prop="">
          <el-input v-model="temp.nickName" />
        </el-form-item>
        <el-form-item label="店铺id" prop="">
          <el-input v-model="temp.storeId" />
        </el-form-item>
        <el-form-item label="备注" prop="">
          <el-input v-model="temp.note" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { memberList, updateMember, addMember, deleteMember } from '@/api/member'
import { villageList } from '@/api/village'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  name: 'MemberManger',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        online: 'success',
        offline: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: false,
      listQuery: {
        pageNum: 1,
        pageSize: 20,
        nickName: ''
      },
      temp: {
        username: '',
        password: '',
        storeId: '',
        note: ''
      },

      dialogFormVisible: false,
      dialogForm2Visible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '添加'
      },
      storeId: 0,
      adminId: 0,
      rules: {
        username: [{ required: true, message: '帐号不能为空！', trigger: 'change' }],
        password: [{ required: true, message: '密码不能为空！', trigger: 'change' }]
      },
      downloadLoading: false
    }
  },
  created() {
    // this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      memberList(this.listQuery).then(response => {
        this.list = response.data.items
        this.total = response.data.total
        // console.log(response)
        // Just to simulate the time of the request
        this.listLoading = false
      },
      error => {
        console.log(error)
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },

    resetTemp() {
      this.temp = {
        username: '',
        password: '',
        storeId: '',
        note: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addMember(this.temp).then(response => {
            this.list.unshift(response.data)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateMember(tempData.id, tempData).then(response => {
            for (const v of this.list) {
              if (v.id === this.temp.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.temp)
                break
              }
            }
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row) {
      const index = this.list.indexOf(row)
      this.$confirm('您确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteMember(row.id).then(response => {
          this.list.splice(index, 1)
          this.$notify({
            title: 'Success',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleSetManageStore(row) {
      villageList().then(response => {
        this.dialogForm2Visible = true
        // eslint-disable-next-line no-array-constructor
        this.storeOptions = new Array()
        this.storeOptions.push({ key: 0, display_name: '未设置' })
        var curStores = response.data.items
        for (var i = 0; i < curStores.length; i++) {
          // console.log('i==' + i)
          this.storeOptions.push({ key: curStores[i].id, display_name: curStores[i].name })
        }
        this.storeId = row.storeId
        this.adminId = row.id
        // console.log('rowId=' + row.storeId)
      })
    }
  }

}
</script>
<style scoped>
</style>
